package uk.ac.aber.paws.client.core;

/**
 * @author Rob Johnson, Aberystwyth University
 * @email rob.johnson@aber.ac.uk
 * @date 16th August 2011
 * 
 * PAWSClientStopper.java
 * 
 * Contains all generic constants used within the application
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.io.ObjectOutputStream;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import uk.ac.aber.paws.client.config.ConfigManager;
import static uk.ac.aber.paws.client.constants.NetworkConstants.*;

public class PAWSClientStopper {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		// load configuration file - the path to this is expected as parameter 1
		String mainConfigPath = args[0];
							
		// load the config file
		ConfigManager mainConfig = new ConfigManager(mainConfigPath,null,false);
		
		boolean sendResult = sendStopMessage(Integer.parseInt(mainConfig.getProperty("app.main.net.secureservercommsport")));		
		
		System.exit(sendResult == true ? 0 : 1);
	}
	
	private static boolean sendStopMessage(int port) {
		
		try {
			SSLSocketFactory SSLSocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
			SSLSocket socket = (SSLSocket)SSLSocketfactory.createSocket("127.0.0.1",port);
			
			final String[] enabledCipherSuites = { "SSL_DH_anon_WITH_RC4_128_MD5" };
		    socket.setEnabledCipherSuites(enabledCipherSuites);
		    
			socket.setSoTimeout(2000);
			
			ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());             
			oos.writeObject(SEND_STOP_MESSAGE); 
			                       
			socket.close();
			
		}
		catch (java.net.SocketTimeoutException ex) {
			return false;
		}
		catch (Exception ex)  {
			return false;
		}
		
		return true;
	}
}
